package org.taobao.ibatiside.ui.action;

import org.apache.commons.lang.StringUtils;
import org.eclipse.datatools.sqltools.sqleditor.SQLEditor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;

public abstract class SqlEditorAction extends Action implements ISelectionChangedListener {
	
	protected SQLEditor editor;
	protected boolean inSourcePage = true;
	public void setEditor(SQLEditor editor) {
		this.editor = editor;
		if (this.editor != null){
			this.editor.getSelectionProvider().addSelectionChangedListener(this);
		}
	}
	@Override
	public void selectionChanged(SelectionChangedEvent event) {
		if (event.getSelection() instanceof ITextSelection)
        {
            update();
        }
	}
	public SQLEditor getEditor() {
		return editor;
	}
	protected void update(){
		setEnabled(inSourcePage && editor != null && editor.isConnected() && StringUtils.isNotBlank(editor.getSelectedText()));		
	}
	public void update(boolean isSQLEditorPage)
    {
       inSourcePage = isSQLEditorPage;
       update();
    }
	protected void dispose() {
		editor = null;
	}
}
